package com.andy.nature.ui.adapter

import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.drawToBitmap
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.andy.base.utils.MVUtils
import com.andy.common.extend.formatMilliSecondTime
import com.andy.common.extend.formatTime
import com.andy.common.model.Label
import com.andy.common.model.Work
import com.andy.image.ext.loadHttpUrl
import com.andy.nature.databinding.AdapterPosterItemBinding
import com.andy.nature.databinding.AdapterTotalItemBinding
import com.andy.nature.ui.activity.LoginActivity
import com.andy.nature.utils.ImageUtils
import com.andy.nature.utils.ShareUtils
import com.cloud.tmc.zxinglib.qrcode.QrCodeUtil
import dp

/**
 * Author:Andy
 * Date:2023/3/20 19:25
 * Description:PosterAdapter
 */
class PosterAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var workList: MutableList<Work> = mutableListOf()
    private var labelList: MutableList<Label> = mutableListOf()
    private var sharePostList: MutableList<String> = mutableListOf()

    companion object {
        const val TYPE_TOTAL = 0
        const val TYPE_ITEM = 1
    }

    fun setData(workData: List<Work>, labelData: List<Label>) {
        workList.clear()
        workList.addAll(workData)
        labelList.clear()
        labelList.addAll(labelData)
        sharePostList.clear()
        notifyDataSetChanged()
    }

    fun getSharePostList(): MutableList<String> {
        return sharePostList
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        return if (viewType == 0) {
            ArticleViewHolder(AdapterTotalItemBinding.inflate(layoutInflater, parent, false))
        } else {
            ArticleViewHolder(AdapterPosterItemBinding.inflate(layoutInflater, parent, false))
        }
    }

    override fun getItemViewType(position: Int): Int {
        val data = workList[position]
        return if (data.name == "汇总") {
            TYPE_TOTAL
        } else {
            TYPE_ITEM
        }
    }

    override fun getItemCount(): Int {
        return workList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val data = workList[position]
        if (holder.itemViewType == 0) {
            (((holder as ArticleViewHolder).binding) as AdapterTotalItemBinding).apply {
                tvLabel.text = "企业推荐${data.selectLabel?.name ?: "标签信息"}"
                tvDate.text = getDate()
                rvList.apply {
                    layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
                    val mAdapter = TotalLabelAdapter()
                    adapter = mAdapter
                    mAdapter.setData(data.selectLabel, data.workList, labelList)
                }
                val telephone = MVUtils.getString(LoginActivity.KEY_TEL, "")
                tvDesc.text = tvDesc.context.getString(com.andy.base.R.string.share_total_hint, telephone)
                val qrCodePath = "https://wq.wdxzt.top/app/index.php?i=129&c=entry&m=renlihr_recruit&do=index&fromid=${telephone}"
                val qrBitmap = QrCodeUtil.createQRImage(38.dp, 38.dp, qrCodePath, null)
                ivQrCode.setImageBitmap(qrBitmap)
                rootView.postDelayed({ saveAsImage(rootView, data) }, 1000)
            }
        } else {
            (((holder as ArticleViewHolder).binding) as AdapterPosterItemBinding).apply {
                tvDate.text = data.danzi_date
                tvTitle.isGone = data.name?.trim().isNullOrEmpty()
                tvTitle.text = data.name
                tvEwsr.isGone = data.cj_ewsr?.trim().isNullOrEmpty()
                tvEwsr.text = "额外收入：${data.cj_ewsr ?: ""}"
                tvAddress.isGone = data.qy?.address?.trim().isNullOrEmpty()
                tvAddress.text = data.qy?.address ?: ""
                val m0 = data.demand?.replace("<p>", "")?.replace("</p> ", "")
                tvZpyq.isGone = data.demand?.trim().isNullOrEmpty()
                tvZpyq.text = Html.fromHtml(m0)
                tvGjje.isGone = data.labour?.trim().isNullOrEmpty()
                tvGjje.text = "工价${Html.fromHtml(data.labour?.trim())}"
                tvBtje.isGone = data.subsidize?.trim().isNullOrEmpty()
                tvBtje.text = "补贴${Html.fromHtml(data.subsidize?.trim())}"
                tvSrzc1.isGone = data.sr1.isNullOrEmpty()
                tvSrzc1.text = "收入1：${data.sr1}"
                tvGjsm1.isGone = data.sr1_desc.isNullOrEmpty()
                tvGjsm1.text = "工价说明：${data.sr1_desc}"
                tvSrzc2.isGone = data.sr2.isNullOrEmpty()
                tvSrzc2.text = "收入2：${data.sr2}"
                tvGjsm2.isGone = data.sr2_desc.isNullOrEmpty()
                tvGjsm2.text == "工价说明：${data.sr2_desc}"
                tvSrzc3.isGone = data.sr3.isNullOrEmpty()
                tvSrzc3.text = "收入3：${data.sr3}"
                tvGjsm3.isGone = data.sr3_desc.isNullOrEmpty()
                tvGjsm3.text == "工价说明：${data.sr3_desc}"
                tvZhsr.isGone = data.zhsr.isNullOrEmpty()
                tvZhsr.text = "综合收入：${data.zhsr}"
                tvZcsc.isGone = data.zcsc.isNullOrEmpty()
                tvZcsc.text = "政策时长：${data.zcsc}"
                tvBtrq.isGone = data.btrq.isNullOrEmpty()
                tvBtrq.text = "补贴日期：${data.btrq}"
                val m1 = data.welfare?.replace("\r\n", "<br />")?.replace(" ", "")
                tvFlxq.text = Html.fromHtml(m1)
                if (!data.qrcode_url.isNullOrEmpty()) {
                    ivQrcode.loadHttpUrl(data.qrcode_url!!, com.andy.image.R.drawable.ic_avatar_default)
                    ivQrcode.isVisible = true
                    tvHint1.isVisible = true
                } else {
                    ivQrcode.isVisible = false
                    tvHint1.isVisible = false
                }
                rvLabelList.apply {
                    layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false)
                    val mAdapter = DetailLabelAdapter()
                    adapter = mAdapter
                    mAdapter.setData(assembleLabelList(data.label_arr))
                }
                rootView.postDelayed({ saveAsImage(rootView, data) }, 1000)
            }
        }
    }

    internal class ArticleViewHolder(var binding: ViewBinding) : RecyclerView.ViewHolder(binding.root)

    private fun assembleLabelList(ids: List<String>?): MutableList<Label> {
        if (ids.isNullOrEmpty()) {
            return mutableListOf()
        }
        val list = mutableListOf<Label>()
        labelList.forEach {
            if (ids.contains(it.id)) {
                list.add(it)
            }
        }
        return list
    }

    private fun saveAsImage(rootView: View, work: Work) {
        val bitmap = rootView.drawToBitmap()
        val fileName = "share_${work.id}.jpg"
        val savePath = ImageUtils.saveImageToGallery(rootView.context, bitmap, fileName) ?: ""
        if (savePath.isNotEmpty()) {
            sharePostList.add(savePath)
        }
    }

    private fun getDate(): String {
        val current = System.currentTimeMillis()
        val tmp = current.formatTime()
        val tamp = ShareUtils.dateToStamp("$tmp 15:00:00")
        val date = if (current > tamp) {
            (current + 24 * 60 * 60 * 1000).formatMilliSecondTime()
        } else {
            current.formatMilliSecondTime()
        }
        return date
    }
}